package me.zhengjie.modules.quartz.config

import me.zhengjie.logging.slf4j.logError
import org.quartz.*
import org.quartz.spi.TriggerFiredBundle
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Scope
import org.springframework.scheduling.quartz.AdaptableJobFactory
import org.springframework.scheduling.quartz.SchedulerFactoryBean
import org.springframework.stereotype.Component

/**
 * 定时任务配置
 * @author /
 * @date 2019-01-07
 */
@Configuration
@Scope("singleton")
class QuartzConfig {
    /**
     * 解决Job中注入Spring Bean为null的问题
     */
    @Component("quartzJobFactory")
    class QuartzJobFactory(private val capableBeanFactory: AutowireCapableBeanFactory) : AdaptableJobFactory() {
        @Throws(Exception::class)
        override fun createJobInstance(bundle: TriggerFiredBundle): Any {
            try {
                // 调用父类的方法，把Job注入到spring中
                val jobInstance = super.createJobInstance(bundle)
                capableBeanFactory.autowireBean(jobInstance)
                return jobInstance
            }catch (e: Exception) {
                logError("创建job实例失败!"+e.message!!)
                throw RuntimeException(e)
            }
        }
    }

    /**
     * 注入scheduler到spring
     * @param quartzJobFactory /
     * @return Scheduler
     * @throws Exception /
     */
    @Bean(name = ["scheduler"])
    @Throws(Exception::class)
    fun scheduler(quartzJobFactory: QuartzJobFactory?): Scheduler {
        val factoryBean = SchedulerFactoryBean()
        factoryBean.setJobFactory(quartzJobFactory!!)
        factoryBean.afterPropertiesSet()
        val scheduler = factoryBean.scheduler
        scheduler.start()
        return scheduler
    }
}